package com.whyvent.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.whyvent.entity.MUser;
import com.whyvent.service.IMUserService;
import com.whyvent.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.annotations.Result;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author WhyVent
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Resource
    JwtUtils jwtUtils;

    @Resource
    IMUserService userService;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        MUser user = userService.getById(Long.valueOf(userId));
        if (user==null){
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus()==-1){
            throw new LockedAccountException("账户已被锁定");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user,profile);
        System.out.println("--------------------");
        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
